using System.Collections.Generic;

namespace IntetfaceEditor4PDA
{
    public class ParamItem
    {
        public int IDParam = 0;
        public string TableName;
        public bool IsGrid;
        public string MenuText;
        public int IDParent = -1;
        public int IDTopPanel = -1;
        public string Order;
        public List<ParamItem> Child = new List<ParamItem>();
        /// <summary>
        /// Adds new ParamItem record to list accordin to its IDParam and IDParent. 
        /// Procedure Searches if there is olready items with IDParent equal to inserting IDParent 
        /// and reorganize list
        ///  </summary>
        /// <param name="ListOfTop">The list of ParamItems.</param>
        /// <param name="newItem">The new item.</param>
        public static void AddToList(List<ParamItem> ListOfTop, ParamItem newItem)
        {
            // search parent
            bool found = true;
            while (found)
            {
                found = false;
                foreach (ParamItem item in ListOfTop)
                {
                    if (item.IDParent == newItem.IDParam)
                    {
                        found = true;
                        newItem.Child.Add(item);
                        ListOfTop.Remove(item);
                        break;
                    }
                }
            }
            foreach (ParamItem item in ListOfTop)
            {
                if(item.IDParam == newItem.IDParent)
                {
                    item.Child.Add(newItem);
                    return;
                }
            }
            ListOfTop.Add(newItem);  
        }

        public static void Update(ParamItem item)
        {
            if(item.IDParent == -1)
            {
                new QueryExec().Execute(
                    string.Format(SQLControlsReader.UpadteSheetTopItemName, item.IDParam, item.MenuText));
            }
            else
            {
                new QueryExec().Execute(
                    string.Format(SQLControlsReader.UpadteSheetChildItemName, item.IDParam, item.MenuText, item.IsGrid?1:0, item.TableName,item.Order));
            }
        }
    }
}